<?php 
namespace Special\Service;
class SpecialService
{
	private $db, $type_db, $c_db, $data_db;
	public $pages;
	function __construct() {
		$this->db = D('Special'); //专题数据模型
		$this->c_db = D('SpecialContent'); //专题内容数据模型
		$this->data_db = D('SpecialCData');
		$this->pages = '';
	}


	/**
	 * 调取内容信息
	 * @param intval $modelid 模型ID
	 * @param string $where sql语句
	 * @param intval $page 分页
	 * @return array 返回调取的数据 
	 */
	public function _get_import_data($modelid = 0, $where = '', $page) {
		$models = getcache('model', 'commons');
		$tableName = $models[$modelid]['tablename'];
		if(!$modelid || !$tableName) return '';
		$count = M($tableName)->where($where)->count();
		$data = M($tableName)->where($where)->page($page, 10)->select();
		$this->pages = page($count, 10);
		return $data;
	}

	/**
	 * 导入模型数据到专题
	 * @param  int  $specialid 专题ID
	 * @param  int  $modelid   模型ID
	 * @param  int  $id        文档ID
	 * @param  int 	$listorder 排序
	 * @return bool
	 */
	public function _import($specialid, $modelid, $id, $listorder = 0) {
		if (!$specialid || !$id || !$modelid) return false;
		$models = getcache('model', 'commons');
		$tableName = $models[$modelid]['tablename'];
		$info = M($tableName)->field('id, catid, title, thumb, url, description, username, inputtime, updatetime')->find($id);
		if ($info) {
			$info['curl'] = $info['id'].'|'.$info['catid'];
			unset($info['id'], $info['catid']);
			$count = $this->c_db->where(array('title'=>addslashes($info['title']), 'specialid'=>$specialid))->count();
			if(!$count) {
				$info['specialid'] = $specialid;
				$info['islink'] = 1;
				$info['listorder'] = $listorder;
				return $this->c_db->add($info);
			}
		}
		return false;
	}

	/* 删除专题 */
	public function _delete_special($specialid) {
		$specialid = (int) $specialid;
		if ($specialid < 1) return FALSE;
		$ids = $this->c_db->where(array('specialid' => $specialid))->getField('id', TRUE);
		/* 循环删除信息 */
		if ($ids) {
			foreach ($ids as $id) {
				$this->_delete_content($id);
			}
		}
		$this->db->delete($specialid);
		return TRUE;
	}

	/* 删除信息 */
	public function _delete_content($id) {
		$id = (int) $id;
		if($id < 1) return FALSE;
		$info = $this->c_db->getById($id);
		if ($info['isdata']) {
			$this->data_db->delete($id);
		}
		/* 删除统计表 */
		$hitsid = 'special-c-'.$info['specialid'].'-'.$id;
		D('Hits')->where(array('hitsid'=>$hitsid))->delete();

		$this->c_db->delete($id); //删除内容表数据
		return TRUE;
	}

}